package  {
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import org.flixel.FlxText;
	import org.flixel.FlxG;
	import org.flixel.FlxState;

	public class MainMenuState extends FlxState {
		
		private var hrm:HeartRateMonitor;
		private var titleTxt:FlxText;
		private var startTxt:FlxText;
		private var starting:Boolean = false;
		private var mainMenu:Boolean;
		private var delayTimer:Timer;
		private var delayFlag:Boolean = false;
		
		public function MainMenuState(mainMenu:Boolean=true) {
			super();
			this.mainMenu = mainMenu;
		}
		
		override public function create():void
		{
			FlxG.bgColor = 0xff000000;
			
			if (!mainMenu)
				FlxG.flash(0xff000000, 5);
			
			titleTxt = new FlxText(10, 20, 300);
			titleTxt.text = mainMenu ? "They Tried to Make Me Go to Rehab" : "I Said No, No,\nNo.";
			titleTxt.size = 18;
			titleTxt.color = 0xffffffff;
			titleTxt.alignment = "center";
			this.add(titleTxt);
			
			hrm = new HeartRateMonitor(60, 70, 200, 100, this.add, this.remove, true);
			hrm.setBPM(70);
			hrm.start();
			this.add(hrm);
			
			startTxt = new FlxText(10, 190, 300);
			startTxt.text = mainMenu ? "Press Space to Start" : "Press Space to Replay";
			startTxt.size = 12;
			startTxt.color = 0xffffffff;
			startTxt.alignment = "center";
			this.add(startTxt);
		}
		
		private function switchToMainMenu():void
		{
			mainMenu = true;
			titleTxt.text = "They Tried to Make Me Go to Rehab";
			startTxt.text = "Press Space to Start";
			delayFlag = true;
			delayTimer = new Timer(500, 1);
			delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE, endDelay);
			delayTimer.start();
		}
		
		override public function update():void
		{
			super.update();
			if (!starting && FlxG.keys.SPACE)
			{
				if (mainMenu && !delayFlag)
				{
					start();
				}
				else if (!delayFlag)
				{
					switchToMainMenu();
				}
			}
				
			hrm.update();
		}
		
		private function endDelay(event:TimerEvent):void
		{
			delayFlag = false;
		}
		
		private function start():void
		{
			starting = true;
			this.remove(titleTxt);
			this.remove(startTxt);
			hrm.stop(3);
			FlxG.fade(0xff000000, 3, onFadeComplete);
		}
		
		private function onFadeComplete():void
		{
			FlxG.sounds.kill();
			FlxG.switchState(new PlayState(1, false));
		}
	}
}
